//
//  QTProductDetailViewController.m
//  qdqts
//
//  Created by jonn on 14-6-9.
//  Copyright (c) 2014年 seas.cheng. All rights reserved.
//

#import "QTProductDetailViewController.h"
#import "Global.h"
#import "QTInfoTableViewCell.h"
#import "QTManTableViewCell.h"
#import "QTPriceTableViewCell.h"
#import "QTReportTableViewCell.h"
#import "QTButtonTableViewCell.h"
#import "UIImageView+UIActivityIndicatorForSDWebImage.h"
#import "QTProductHistoryElement.h"
#import "QTEvaluateViewController.h"

#import "Product.h"
#import "QTProductPersistence.h"

@interface QTProductDetailViewController ()

@end

@implementation QTProductDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"商品详情";
    
    NSLog(@"_puid%@",_puid);
    
    _buttonViewController=[[QTButtonViewController alloc] init];
    _buttonViewController.view.frame=CGRectMake(0, 0, SCREEN_WIDTH, 60);
    _buttonViewController.tablViewButtonDelegate=self;
    
    //这个445是怎么来的:
    //正确值应为SCREEN_HEIGHT-(NAVBAR_HEIGHT+TABBAR_HEIGHT)。4.0中此值为455，合适。但3.5中确不合适，而455.0在3.0同样合适。于是定值455
    NSLog(@"SCREEN_HEIGHT-NAVBAR_HEIGHTTABBAR_HEIGHT:%f",SCREEN_HEIGHT-NAVBAR_HEIGHT-TABBAR_HEIGHT);
    //_tableView=[[UITableView alloc] initWithFrame:CGRectMake(0,NAVBAR_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT-(NAVBAR_HEIGHT+TABBAR_HEIGHT)) style:UITableViewStyleGrouped];
    
    _tableView=[[UITableView alloc] initWithFrame:CGRectMake(0,NAVBAR_HEIGHT,SCREEN_WIDTH,SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    
    UIView *headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.1)];
    _tableView.tableHeaderView=headerView;

    
    _tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleBottomMargin);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    [_activity startAnimating];
    [_activity setHidesWhenStopped:YES];
    [_failure setHidden:YES];
    [_tableView setHidden:YES];
    
    
    [[QSClient instance] loadProductDetail:_puid barCode:_barCode completionBlock:^(ProductDetail *productDetail, NSError *error) {
        //NSLog(@"Result:%@",productDetail);
        if (error) {
//            self.failure.text=@"无法连接服务器，请检查网络";
//            [self.failure setHidden:NO];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:[NSString stringWithFormat:@"无法连接服务器，请稍后在试",nil]
                                                         delegate:self
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles:nil, nil];
            [alert show];
        }
        else if (productDetail==NULL) {
            [_activity stopAnimating];
            [_failure setHidden:NO];
        }else{
            _failure.hidden=YES;
            [[QSClient instance] findEnterpriseInfoById:productDetail.productInfoDetail.puid completionBlock:^(EnterpriseInfo *enterpriseInfo, NSError *error) {
                [_activity stopAnimating];
                [_tableView setHidden:NO];
                self.enterpriseInfo=enterpriseInfo;
                self.productDetail=productDetail;
                self.reportCount=[self.productDetail.reportList count];
                self.priceCount=[self.productDetail.productInfoDetail.productPrice count];
                
                _buttonViewController.name_1.text=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:0]).name;
                _buttonViewController.id_1=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:0]).puid;
               // _buttonViewController.num_1.text=[((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:0]).num stringByAppendingString:@"条评价"];
                _buttonViewController.name_2.text=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:1]).name;
                _buttonViewController.id_2=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:1]).puid;
                //_buttonViewController.num_2.text=[((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:1]).num stringByAppendingString:@"条评价"];
                _buttonViewController.name_3.text=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:2]).name;
                _buttonViewController.id_3=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:2]).puid;
                //_buttonViewController.num_3.text=[((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:2]).num stringByAppendingString:@"条评价"];
            
                [_tableView reloadData];
                
                //-----------------------Persistence---------------------
                //NSError *err;
                Product *product=[[Product alloc] init];
                product.puid=productDetail.productInfoDetail.puid;
                product.productName=productDetail.productInfoDetail.productName;
                product.filePath=productDetail.productInfoDetail.productUrl;
                product.date=[[NSDate alloc] init];
                QTProductPersistence *persistence=[[QTProductPersistence alloc] init];
                BOOL save=[persistence saveHistory:product];
                if (save==NO) {
                    NSLog(@"Save ERROR!");
                }
                
                
                NSArray *array=[persistence getHistory];
                NSLog(@"getHistory:%@",array);
                //-----------------------------------------------------------
                
            }];
        }
    }];
    
    
    //[self tableView:_tableView sectionForSectionIndexTitle:@"1" atIndex:0];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



#pragma mark - Table view data source

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section==3) {
        return _buttonViewController.view;
    }
    else
        return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    NSInteger count = 0;
    if (section == 3) {
        count = 60.0f;
    }
    return count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    switch (section) {
        case 2:
            if (self.reportCount==0) {
                return  1;
            }else return self.reportCount;
            break;
        case 3:
            if (self.priceCount==0) {
                return  1;
            }else return self.priceCount;
        default:
            return 1;
            break;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat count=0;
    switch (indexPath.section) {
        case 0:
            count=144;
            break;
        case 1:
            count=200;
            break;
//        case 4:
//            count=90;
//            break;
        default:
            count=50;
            break;
    }
    return count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0.1;
    }else
        return 35.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, 35.0)];
    UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    headerLabel.backgroundColor = [UIColor clearColor];
    headerLabel.font = [UIFont boldSystemFontOfSize:12];
    headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 35.0);
    headerLabel.enabled=NO;
    
    switch (section) {
            case 1:
                headerLabel.text =  @"企业信息";
                break;
            case 2:
                headerLabel.text =  @"抽检报告";
                break;
            case 3:
                headerLabel.text =  @"店商价格（仅供参考）";
                break;
        default:
            break;
    }
    
    [customView addSubview:headerLabel];
    customView.backgroundColor=[UIColor whiteColor];
    return customView;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    static NSString *infoCellStr =@"infoCell";
    static NSString *manCellStr =@"manCell";
    static NSString *reportCellStr =@"resultCell";
    static NSString *priceCellStr =@"priceCell";
    static NSString *buttonCellStr =@"buttonCell";
    
    //自定义cell
    QTInfoTableViewCell *infoCell = (QTInfoTableViewCell *)[tableView dequeueReusableCellWithIdentifier:infoCellStr];
    if(infoCell ==nil) {
        NSArray *nibArray = [[NSBundle mainBundle]loadNibNamed:@"QTInfoTableViewCell"owner:self options:nil];
        infoCell = (QTInfoTableViewCell *)[nibArray objectAtIndex:0];
    }

    QTManTableViewCell *manCell = (QTManTableViewCell *)[tableView dequeueReusableCellWithIdentifier:manCellStr];
    if(manCell ==nil) {
        NSArray *nibArray = [[NSBundle mainBundle]loadNibNamed:@"QTManTableViewCell"owner:self options:nil];
        manCell = (QTManTableViewCell *)[nibArray objectAtIndex:0];
    }
    
    QTReportTableViewCell *reportCell = (QTReportTableViewCell *)[tableView dequeueReusableCellWithIdentifier:reportCellStr];
    if(reportCell ==nil) {
        NSArray *nibArray = [[NSBundle mainBundle]loadNibNamed:@"QTReportTableViewCell"owner:self options:nil];
        reportCell = (QTReportTableViewCell *)[nibArray objectAtIndex:0];
        
    }
    
    QTPriceTableViewCell *priceCell = (QTPriceTableViewCell *)[tableView dequeueReusableCellWithIdentifier:priceCellStr];
    if(priceCell ==nil) {
        NSArray *nibArray = [[NSBundle mainBundle]loadNibNamed:@"QTPriceTableViewCell"owner:self options:nil];
        priceCell = (QTPriceTableViewCell *)[nibArray objectAtIndex:0];
        
    }
    
    QTButtonTableViewCell *buttonCell = (QTButtonTableViewCell *)[tableView dequeueReusableCellWithIdentifier:buttonCellStr];
    if(buttonCell ==nil) {
        NSArray *nibArray = [[NSBundle mainBundle]loadNibNamed:@"QTButtonTableViewCell"owner:self options:nil];
        buttonCell = (QTButtonTableViewCell *)[nibArray objectAtIndex:0];
    }
    
    switch (indexPath.section) {
        case 0:
        {
            NSString *picURL=_productDetail.productInfoDetail.productUrl;
            [infoCell.productImage setImageWithURL:[NSURL URLWithString:[self convertPicURL:picURL]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
                if (image == nil) {
                    [infoCell.productImage setImage:[UIImage imageNamed:@"暂无图片.png"]];
                }
            } usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray ];

            infoCell.productName.text=_productDetail.productInfoDetail.productName;
            infoCell.productType.text=_productDetail.productInfoDetail.productType;
            infoCell.brand.text=_productDetail.productInfoDetail.brand;
            [infoCell.rateView setImagesDeselected:@"startNull.png" partlySelected:@"starHalf.png" fullSelected:@"starFull.png"];
            [infoCell.rateView displayRating:[_productDetail.percent floatValue]];
            infoCell.selectionStyle=NO;
            return infoCell;
            break;
        }
        case 1:
        {
            AppEnterpriseInfo  *appEnterpriseInfo=_enterpriseInfo.appEnterpriseInfo;
            manCell.selectionStyle=NO;
            manCell.enterpriseEmail.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.enterpriseEmail);
            manCell.enterpriseUrl.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.enterpriseUrl);
            manCell.enterprisePost.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.enterprisePost);
            manCell.capital.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.capital);
            manCell.enterpriseAddress.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.enterpriseAddress);
            manCell.scope.text=([appEnterpriseInfo.scope isEqualToString:@""]?@"暂无":appEnterpriseInfo.scope);
            manCell.registerNumber.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.registerNumber);
            manCell.registerAddress.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.registerAddress);
            manCell.empowerRegister.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.empowerRegister);
            manCell.organizationCode.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.organizationCode);
            manCell.startTime.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.startTime);
            manCell.term.text=([appEnterpriseInfo.enterprisePost isEqualToString:@""]?@"暂无":appEnterpriseInfo.term);
            return manCell;
            break;
        }
        case 2:
            if (self.reportCount==0) {
                reportCell.labelName.text=@"暂无记录";
                reportCell.selectionStyle=NO;
                reportCell.userInteractionEnabled=NO;
                
            }else{
                reportCell.textView.text=((ReportList *)[self.productDetail.reportList objectAtIndex:indexPath.row]).title;
                
                reportCell.labelName.text=((ReportList *)[self.productDetail.reportList objectAtIndex:indexPath.row]).title;
                NSString *pass=((ReportList *)[self.productDetail.reportList objectAtIndex:indexPath.row]).pass;
                if ([pass isEqualToString:@"yes"]) {
                    [reportCell.cellImage setImage:[UIImage imageNamed:@"pass_YES"]];
                }else [reportCell.cellImage setImage:[UIImage imageNamed:@"pass_NO"]];
                reportCell.selectionStyle=YES;
            }
            return reportCell;
            break;
        case 3:
            if (self.priceCount==0) {
                priceCell.cellName.text=@"暂无记录";
            }else{
                priceCell.cellName.text=((ProductDetailPrice *)[self.productDetail.productInfoDetail.productPrice objectAtIndex:indexPath.row]).shopName;
                if ([priceCell.cellName.text isEqualToString:@"京东商城"]) {
                    [priceCell.cellImage setImage:[UIImage imageNamed:@"shop_JD"]];
                }else if ([priceCell.cellName.text isEqualToString:@"天猫商城"]){
                    [priceCell.cellImage setImage:[UIImage imageNamed:@"shop_Tmall"]];
                }else if([priceCell.cellName.text isEqualToString:@"1号店"]){
                    [priceCell.cellImage setImage:[UIImage imageNamed:@"shop_1"]];
                }else if([priceCell.cellName.text isEqualToString:@"亚马逊"]){
                    [priceCell.cellImage setImage:[UIImage imageNamed:@"shop_amazon"]];
                }else if([priceCell.cellName.text isEqualToString:@"当当"]){
                    [priceCell.cellImage setImage:[UIImage imageNamed:@"shop_dangdang"]];
                }else if([priceCell.cellName.text isEqualToString:@"国美在线"]){
                    [priceCell.cellImage setImage:[UIImage imageNamed:@"shop_gnome"]];
                }else if([priceCell.cellName.text isEqualToString:@"苏宁电器"]){
                    [priceCell.cellImage setImage:[UIImage imageNamed:@"shop_suning"]];
                }
                NSString *shopPrice=((ProductDetailPrice *)[self.productDetail.productInfoDetail.productPrice objectAtIndex:indexPath.row]).shopPrice;
                priceCell.cellPrice.text=[@"￥" stringByAppendingString:shopPrice==nil?@"":shopPrice];
            }
            priceCell.selectionStyle=NO;
            return priceCell;
//        case 4:
//            buttonCell.btn_1.layer.masksToBounds=YES;
//            buttonCell.btn_1.layer.cornerRadius = 5.0;
//            buttonCell.btn_1.layer.borderWidth = 1;
//            buttonCell.btn_1.layer.borderColor=[GREENCOLOR CGColor];
//            buttonCell.name_1.text=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:0]).name;
//            buttonCell.num_1.text=[((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:0]).num stringByAppendingString:@"条评价"];
//            
//            buttonCell.btn_2.layer.masksToBounds=YES;
//            buttonCell.btn_2.layer.cornerRadius = 5.0;
//            buttonCell.btn_2.layer.borderWidth = 1;
//            buttonCell.btn_2.layer.borderColor=[GREENCOLOR CGColor];
//            buttonCell.name_2.text=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:1]).name;
//            buttonCell.num_2.text=[((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:1]).num stringByAppendingString:@"条评价"];
//            
//            buttonCell.btn_3.layer.masksToBounds=YES;
//            buttonCell.btn_3.layer.cornerRadius = 5.0;
//            buttonCell.btn_3.layer.borderWidth = 1;
//            buttonCell.btn_3.layer.borderColor=[GREENCOLOR CGColor];
//            buttonCell.name_3.text=((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:2]).name;
//            buttonCell.num_3.text=[((ProductEvaluate *)[_productDetail.productInfoDetail.productEvaluate objectAtIndex:2]).num stringByAppendingString:@"条评价"];
//        
//            buttonCell.selectionStyle=NO;
//            return buttonCell;
//            break;
        default:
            return cell;
            break;
    }
    
}


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==2) {
        NSLog(@"抽检报告");
        NSString *url=[qsServerUrl stringByAppendingString:((ReportList *)[self.productDetail.reportList objectAtIndex:indexPath.row]).url];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
}


-(void)clickButton:(NSString *)id name:(NSString *)name{
    NSLog(@"ButoonClick:%@",id);
    QTEvaluateViewController *evaluateViewController=[[QTEvaluateViewController alloc] init];
    evaluateViewController.puid=_puid;
    evaluateViewController.name=name;
    evaluateViewController.type=id;
    [self.navigationController pushViewController:evaluateViewController animated:YES];
}


-(NSString *)convertPicURL:(NSString *)url
{
    NSString *picURL=url;
    NSRange range_http = [url rangeOfString:@"http:"];
    NSRange range_HTTP = [url rangeOfString:@"HTTP:"];
    if ((range_http.length==0)&&(range_HTTP.length==0)) {
        picURL=[productInfoPicUrl stringByAppendingString:url==nil?@"":url];
    }
    return  picURL;
}

@end
